package com.bankcomm.ui.specialwidget;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import com.bankcomm.R;
import com.bankcomm.bean.GroupCity;
import com.bankcomm.bean.ItemCity;
import com.bankcomm.util.LPUtils;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.utils.Utils;

/**
 * 城市选择控件
 * 
 * @author zhang.h
 * 
 * @date 2012-6-29 下午04:02:23
 */
public class MyCityChoose extends EditText {
	Context context_;
	
	/** 默认显示列数 */
	private int col = 4;

	/** 城市选择界面外层布局 */
	private LinearLayout outerLL;

	/** 滚动布局 */
	private ScrollView sv;

	/** 城市选择界面内层布局 */
	private LinearLayout interLL;

	/** 每行布局 */
	private LinearLayout rowLL = null;

	// 单个城市控件的宽高(高度默认为20)
	private int CITY_RB_WIDTH = 0;
	private int CITY_RB_HEIGHT = 0;

	// 所有RB城市集合
	private List<CityRadioButton> rbs = new ArrayList<CityRadioButton>();

	private int SV_PADDING_TOP = Utils.getScaledValueY(0);

	/** 布局参数 */
	LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);

	/** 分组城市集合 */
	private List<GroupCity> groupCities = null;

	private Dialog dialog;
	
	private Bitmap checkBitmap = null;

	private String cityValue;

	private String cityId;
	
	public MyCityChoose(Context context) {
		super(context);
		// init(context);
	}

	public MyCityChoose(Context context, AttributeSet attrs) {
		super(context, attrs);
		// init(context);
	}

	public MyCityChoose(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// init(context);
	}

	public void init(Context context, String cityJson) {
		
		context_ = context;

		initWH();
		// 初始化分组城市数据
		initCityDatas(cityJson);

		// 生成城市控件
		generateCityView(context);

		// 初始化默认值
		initDefaultValue();

		// 初始化PopupWindow
		initPW();
	}

	//初始化每个城市的宽高
	private void initWH() {
		// TODO Auto-generated method stub
		CITY_RB_WIDTH = (int) (LPUtils.screenwidth*1.0f / col*1.0f);
		
		if(null == checkBitmap){
			checkBitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.checkcity)).getBitmap();				
		}
		
		CITY_RB_HEIGHT = Math.max(checkBitmap.getHeight(),Utils.getScaledValueX(25));
	}

	private void initDefaultValue() {
		
		String saveCity = PackageManagerAndroid.ANDROIDDB.get("city_select");
		if (null != saveCity && !"".equalsIgnoreCase(saveCity)) {
			String[] city = saveCity.split("\\|");
			cityValue = city[1];
			cityId = city[0];
		}
		
		if(!saveCity.equals("")){
			MyCityChoose.this.setText(cityValue);
			MyCityChoose.this.setValue(cityValue);
			return;
		}
		
		if (groupCities != null && groupCities.size() > 0) {
			for (int i = 0; i < groupCities.size(); i++) {
				if ((getContext().getString(R.string.hotcity)).equals(groupCities.get(i).getGroupBy())) {
					MyCityChoose.this.setText(groupCities.get(i).getItemCitys().get(0).getName());
					MyCityChoose.this.setValue(groupCities.get(i).getItemCitys().get(0).getValue());
					break;
				}
			}
		}
	}

	private void initCityDatas(String cityJson) {
		try {
			groupCities = new ArrayList<GroupCity>();
			JSONArray citysJA = new JSONArray(cityJson.toString());
			for (int i = 0; i < citysJA.length(); i++) {
				GroupCity groupCity = new GroupCity();
				JSONObject citysJO = (JSONObject) citysJA.get(i);

				// 若是"其他"则通过算法找出分类标识(A-G...)
				String groupText = citysJO.getString("group");
				if (groupText != null && (getContext().getString(R.string.others)).equals(groupText)) {
					List<ItemCity> itemCitys = new ArrayList<ItemCity>();
					JSONArray cityJA = new JSONArray(citysJO.getString("itemCitys"));
					for (int j = 0; j < cityJA.length(); j++) {
						JSONObject cityJO = (JSONObject) cityJA.get(j);
						String cityName = cityJO.getString("name");
						String cityShort = LPUtils.cn2pinyin(cityName); // 得到城市简拼
						ItemCity itemCity = new ItemCity(cityName, cityJO.getString("value"), cityShort);
						itemCitys.add(itemCity);
					}

					// 开始排序
					if (!itemCitys.isEmpty()) {
						Collections.sort(itemCitys, new Comparator<ItemCity>() {
							@Override
							public int compare(ItemCity o1, ItemCity o2) {
								return o1.getSearchkey().toUpperCase().compareTo(o2.getSearchkey().toUpperCase());
							}
						});

						// 排序完后, 对列表加入字母
						char prevch = '0';
						GroupCity currGC = null;
						List<ItemCity> currIC = null;
						for (ItemCity itemCity : itemCitys) {
							char ch = itemCity.getSearchkey().charAt(0);

							// A - G
							if ((ch >= 'A' && ch <= 'G') || (ch >= 'a' && ch <= 'g')) {
								if (prevch != 'A') {
									currIC = new ArrayList<ItemCity>();
									currGC = new GroupCity();
									currGC.setGroupBy("A - G");
								}
								prevch = 'A';
								currIC.add(itemCity);
							}
							// H - N
							else if ((ch >= 'H' && ch <= 'N') || (ch >= 'h' && ch <= 'n')) {
								if (prevch != 'H') {
									currGC.setItemCitys(currIC);
									groupCities.add(currGC);

									currIC = new ArrayList<ItemCity>();
									currGC = new GroupCity();
									currGC.setGroupBy("H - N");
								}
								prevch = 'H';
								currIC.add(itemCity);
							}
							// P - U
							else if ((ch >= 'P' && ch <= 'U') || (ch >= 'p' && ch <= 'u')) {
								if (prevch != 'P') {
									currGC.setItemCitys(currIC);
									groupCities.add(currGC);

									currIC = new ArrayList<ItemCity>();
									currGC = new GroupCity();
									currGC.setGroupBy("P - U");
								}
								prevch = 'P';
								currIC.add(itemCity);
							}
							// W - Z
							else if ((ch >= 'W' && ch <= 'Z') || (ch >= 'w' && ch <= 'z')) {
								if (prevch != 'W') {
									currGC.setItemCitys(currIC);
									groupCities.add(currGC);

									currIC = new ArrayList<ItemCity>();
									currGC = new GroupCity();
									currGC.setGroupBy("W - Z");
								}
								prevch = 'W';
								currIC.add(itemCity);
							}
						}
						currGC.setItemCitys(currIC);
						groupCities.add(currGC);
					}
				} else {
					groupCity.setGroupBy(groupText);

					List<ItemCity> itemCitys = new ArrayList<ItemCity>();
					JSONArray cityJA = new JSONArray(citysJO.getString("itemCitys"));
					for (int j = 0; j < cityJA.length(); j++) {
						JSONObject cityJO = (JSONObject) cityJA.get(j);
						String searchkey = "";
						if (cityJO.has("searchkey")) {
							searchkey = cityJO.getString("searchkey");
						}

						ItemCity itemCity = new ItemCity(cityJO.getString("name"), cityJO.getString("value"), searchkey);

						// 若不为空 , 则添加
						if (itemCity != null) {
							itemCitys.add(itemCity);
						}
					}
					groupCity.setItemCitys(itemCitys);

					// 若不为空 , 则添加
					if (itemCitys != null && itemCitys.size() > 0) {
						groupCities.add(groupCity);
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void generateCityView(Context context) {
		// 外层布局
		outerLL = new LinearLayout(context);
		outerLL.setOrientation(LinearLayout.VERTICAL);
		outerLL.setBackgroundResource(R.drawable.city_choose_bg);
		outerLL.setLayoutParams(lp);

		// 垂直滚动条
		sv = new ScrollView(context);
		sv.setPadding(0, SV_PADDING_TOP, 0, 0);

		// 内层布局
		interLL = new LinearLayout(context);
		interLL.setOrientation(LinearLayout.VERTICAL);

		interLL.removeAllViews();
		sv.removeAllViews();
		outerLL.removeAllViews();

		addRBView(context, rowLL, groupCities, lp);

		sv.addView(interLL);
		outerLL.addView(sv);
	}

	private void addRBView(Context context, LinearLayout rowLL, List<GroupCity> groupCities, LayoutParams lp) {
		int index_ = 0;

		// 添加城市
		if (groupCities != null && groupCities.size() > 0) {
			for (int i = 0; i < groupCities.size(); i++) {
				GroupCity currGC = groupCities.get(i);
				// 分组文本
				String groupText = currGC.getGroupBy();
				TextView gTextView = new TextView(context);
				LinearLayout.LayoutParams gTextViewLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				gTextView.setLayoutParams(gTextViewLP);
				gTextView.setPadding(Utils.getScaledValueX(10), 0, 0, 0);
				gTextView.setGravity(Gravity.CENTER_VERTICAL);
				gTextView.setText(groupText);
				//gTextView.setTextSize(Utils.getFontSize(10));
				gTextView.setTextColor(Color.WHITE);
				gTextView.setBackgroundResource(R.drawable.city_title_bg);
				interLL.addView(gTextView);


				// 分组城市
				List<ItemCity> itmeCitys = currGC.getItemCitys();
				if (itmeCitys != null && itmeCitys.size() > 0) {
					for (int j = 0; j < itmeCitys.size(); j++) {
						index_ = j;
						// 实例化RB
						CityRadioButton currRB = new CityRadioButton(context, currGC.getItemCitys().get(j));
						currRB.setLayoutParams(new LinearLayout.LayoutParams(CITY_RB_WIDTH, CITY_RB_HEIGHT));

						if (j % col == 0) {
							rowLL = new LinearLayout(context);
							rowLL.setOrientation(LinearLayout.HORIZONTAL);
							rowLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
							rowLL.setGravity(Gravity.CENTER_VERTICAL);
							rowLL.addView(currRB);
						} else {
							rowLL.addView(currRB);
							if (j % col == (col - 1)) {
								interLL.addView(rowLL, lp);
							}
						}

						// 存放所有RB城市
						rbs.add(currRB);
					}

					// 处理不足col列场景
					if ((index_ > -1) && ((index_ % col) < (col - 1)) && (rowLL != null)) {
						ViewParent parent_ = rowLL.getParent();
						if (null != parent_) {
							((LinearLayout) parent_).removeView(rowLL);
						}
						interLL.addView(rowLL, lp);
					}
				}
			}
		}
	}

	/**
	 * 单个城市控件
	 */
	class CityRadioButton extends RadioButton {

		private ItemCity currIC;

		public CityRadioButton(Context context, ItemCity itemCity) {
			super(context);
			currIC = itemCity;
			setText(currIC.getName());
			this.setGravity(Gravity.CENTER);
			this.setTextColor(Color.BLACK);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			// TODO Auto-generated method stub
			final Paint paint = getPaint();
			paint.setAntiAlias(true);
			if(isChecked()){
				if(null != checkBitmap){
					canvas.drawBitmap(checkBitmap, (getWidth()-checkBitmap.getWidth())/2, (getHeight()-checkBitmap.getHeight())/2, paint);					
				}
			}
			
			if(null != getText()){
				float y = (getHeight() + paint.getTextSize())/2.0f;
				canvas.drawText((String) getText(), (getWidth()-paint.measureText((String) getText()))/2, y, paint);
			}
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				
					// 清除已选中RB状态
					for (CityRadioButton rb : rbs) {
						if (rb.isChecked()) {
							rb.setChecked(false);
							break;
						}
					}
					// 显示值
					MyCityChoose.this.setText(getText().toString());
					// 提交值
					MyCityChoose.this.setValue(getText().toString());
				    dialog.dismiss();
				break;
			}
			return super.onTouchEvent(event);
		}
	}

	private void initPW() {
        dialog = new Dialog(getContext(),R.style.NoTitleBar);
        dialog.setContentView(outerLL);
        dialog.setCanceledOnTouchOutside(false);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case KeyEvent.ACTION_DOWN:
			this.requestFocus();
			break;
		case KeyEvent.ACTION_UP:
			dialog.show();
			break;
		default:
			return super.onTouchEvent(event);
		}
		return true;
	}

	private String value;

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}
